﻿using Discount.GRPC.Data;
using Discount.GRPC.Model;
using Grpc.Core;
using Mapster;
using Microsoft.EntityFrameworkCore;

namespace Discount.GRPC.Services
{
    public class DiscountService(DiscountDbContext dbContext,ILogger<DiscountService> logger)
        : DiscountProtoService.DiscountProtoServiceBase
    {
        override public async Task<CouponModel> GetDiscount(GetDiscountRequest request, ServerCallContext context)
        {
            logger.LogInformation("GetDiscount called with request {request}", request);
            var coupon=await dbContext.Discounts.FirstOrDefaultAsync(x => x.ProductName == request.ProductName);
            if (coupon == null)
            {
                coupon = new Coupon { ProductName = "No Discount", Amount = 0, Description = "No Discount Desc" };
            }

            var model=coupon.Adapt<CouponModel>();
            return model;
        }

        override public async Task<CouponModel> CreateDiscount(CreateDiscountRequest request, ServerCallContext context)
        {
            var coupon=request.Coupon.Adapt<Coupon>();
            if (coupon == null)
            {
                throw new RpcException(new Status(StatusCode.InvalidArgument, "Coupon is null"));
            }

            dbContext.Discounts.Add(coupon);
           await dbContext.SaveChangesAsync();

            // TODO: Implement discount creation logic here
            var discount = coupon.Adapt<CouponModel>();

            logger.LogInformation("Discount created with {discount}", discount);

            return discount;
        }

        override public async Task<CouponModel> UpdateDiscount(UpdateDiscountRequest request, ServerCallContext context)
        {

            var coupon = request.Coupon.Adapt<Coupon>();
            if (coupon == null)
            {
                throw new RpcException(new Status(StatusCode.InvalidArgument, "Coupon is null"));
            }

            dbContext.Discounts.Update(coupon);
            await dbContext.SaveChangesAsync();

            logger.LogInformation("Discount is successfully updated. ProductName : {ProductName}", coupon.ProductName);

            var couponModel = coupon.Adapt<CouponModel>();
            return couponModel;
        }

        override public async Task<DeleteDiscountResponse> DeleteDiscount(DeleteDiscountRequest request, ServerCallContext context)
        {
            var coupon =await dbContext.Discounts.FirstOrDefaultAsync(x => x.ProductName == request.ProductName);
            if (coupon == null)
            {
                throw new RpcException(new Status(StatusCode.InvalidArgument, "Coupon is null"));
            }

            dbContext.Discounts.Remove(coupon);
            await dbContext.SaveChangesAsync();

            logger.LogInformation("Discount is successfully deleted. ProductName : {ProductName}", coupon.ProductName);

            return new DeleteDiscountResponse { Success = true };
        }

      
    }
}
